const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 添加评论
  async addReview(userId, productId, orderId, rating, content, images = '') {
    // 检查用户是否购买过该商品
    const [orders] = await db.execute(
      'SELECT oi.id FROM order_items oi ' +
      'JOIN orders o ON oi.order_id = o.id ' +
      'WHERE o.user_id = ? AND o.id = ? AND oi.product_id = ? AND o.status = "delivered"',
      [userId, orderId, productId]
    );
    console.log([userId, orderId, productId]);
    
    
    if (orders.length === 0) {
      throw new Error('您尚未购买此商品或订单未完成');
    }
    
    // 检查是否已评论
    const [existingReviews] = await db.execute(
      'SELECT id FROM reviews WHERE user_id = ? AND product_id = ? AND order_id = ?',
      [userId, productId, orderId]
    );
    
    if (existingReviews.length > 0) {
      throw new Error('您已评论过此订单的商品');
    }
    
    // 添加评论
    const [result] = await db.execute(
      'INSERT INTO reviews (user_id, product_id, order_id, rating, content, images) ' +
      'VALUES (?, ?, ?, ?, ?, ?)',
      [userId, productId, orderId, rating, content, images]
    );
    
    // 更新商品平均评分
    await this.updateProductRating(productId);
    
    return result.insertId;
  },

  // 更新商品平均评分
  async updateProductRating(productId) {
    const [reviews] = await db.execute(
      'SELECT AVG(rating) as avg_rating, COUNT(*) as count FROM reviews WHERE product_id = ?',
      [productId]
    );
    
    // 这里可以根据需要将平均评分存储到products表中
    // 例如: UPDATE products SET average_rating = ? WHERE id = ?
  },

  // 获取商品评论
  async getProductReviews(productId, page = 1, limit = 10) {
    const offset = (page - 1) * limit;
    
    const [reviews] = await db.execute(
      'SELECT r.*, u.username, u.avatar FROM reviews r ' +
      'JOIN users u ON r.user_id = u.id ' +
      'WHERE r.product_id = ? ORDER BY r.created_at DESC LIMIT ? OFFSET ?',
      [productId, limit, offset]
    );
    
    // 获取总数用于分页
    const [total] = await db.execute(
      'SELECT COUNT(*) as count FROM reviews WHERE product_id = ?',
      [productId]
    );
    
    // 获取点赞数
    for (const review of reviews) {
      const [likes] = await db.execute(
        'SELECT COUNT(*) as count FROM likes WHERE review_id = ?',
        [review.id]
      );
      review.likes_count = likes[0].count;
    }
    
    return {
      reviews,
      pagination: {
        total: total[0].count,
        page,
        limit,
        totalPages: Math.ceil(total[0].count / limit)
      }
    };
  },

  // 获取用户评论
  async getUserReviews(userId, page = 1, limit = 10) {
    const offset = (page - 1) * limit;
    
    const [reviews] = await db.execute(
      'SELECT r.*, p.name as product_name, p.images as product_images FROM reviews r ' +
      'JOIN products p ON r.product_id = p.id ' +
      'WHERE r.user_id = ? ORDER BY r.created_at DESC LIMIT ? OFFSET ?',
      [userId, limit, offset]
    );
    
    // 获取总数用于分页
    const [total] = await db.execute(
      'SELECT COUNT(*) as count FROM reviews WHERE user_id = ?',
      [userId]
    );
    
    return {
      reviews,
      pagination: {
        total: total[0].count,
        page,
        limit,
        totalPages: Math.ceil(total[0].count / limit)
      }
    };
  },

  // 删除评论
  async deleteReview(userId, reviewId) {
    const [result] = await db.execute(
      'DELETE FROM reviews WHERE id = ? AND user_id = ?',
      [reviewId, userId]
    );
    
    if (result.affectedRows === 0) {
      throw new Error('评论不存在或无权删除');
    }
    
    return true;
  }
};